<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>消息</title>
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/fonts/line-icons.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/main.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/responsive.css">
    <style type="text/css">
        .hz-badge{
            width: 20px;
            height: 20px;
            background-color: #FF5722;
            border-radius: 50%;
            float: right;
            color: white;
            text-align: center;
            line-height: 20px;
            font-weight: bold;
            opacity: 0;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="breadcrumb-wrapper row">
        <div class="col-12 col-lg-3 col-md-6">
            <h4 class="page-title">Chat App</h4>
        </div>
        <div class="col-12 col-lg-9 col-md-6">
            <ol class="breadcrumb float-right">
                <li><a href="../index/index.html">Apps</a></li>
                <li class="active"> / chat App</li>
            </ol>
        </div>
    </div>
</div>
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="chat-main-box">
                    <div class="chat-left-aside">
                        <div class="chat-left-inner">
                            <div class="form-material">
                                <input class="form-control" type="text" placeholder="最近好友">
                            </div>
                            <ul class="chatonline" id="friendList">

                            </ul>
                        </div>
                    </div>
                    <div class="chat-right-aside">
                        <div class="chat-main-header">
                            <div class="p-3 border-bottom">
                                <h4 class="box-title">聊天</h4>
                            </div>
                        </div>
                        <div class="chat-rbox">
                            <div style="height: 550px">
                                <ul class="chat-list p-3" style="overflow-y: auto" id="chatList">

                                </ul>
                            </div>
                            <div class="scrollbar-x-rail">
                                <div class="scrollbar-x"></div>
                            </div>
                            <div class="scrollbar-y-rail">
                                <div class="scrollbar-y"></div>
                            </div>
                        </div>
                        <div class="card-body border-top">
                            <div class="row">
                                <div class="col-8">
                                    <textarea id="sendMessage" placeholder="Type your message here" class="form-control border-0"></textarea>
                                </div>
                                <div class="col-4 text-right">
                                    <button type="button" class="btn btn-common btn-circle btn-lg" id="send"><i class="lni-pointer"></i></button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="../assets/js/jquery-min.js"></script>
<script src="../assets/js/jquery.app.js"></script>
<script src="../assets/js/popper.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/main.js"></script>
<script>
    var ctx = window.parent.ctx;
    //当前用户
    var user = window.parent.user;
    var msgObjArr = new Array();
    var nowP = -1;
    var nowChat = window.parent.nowChat;

    $(function () {
		init();

		$(".hz-badge").click(function () {
            if($(this).text()==='×'){
                var userId = $(this).parent().find('p').text();
                $.ajax({
                    type: "post",
                    url: ctx + "/userFriend/updateRecently",
                    xhrFields:{
                        withCredentials:true
                    },
                    data: {targetUserId: userId,isRecently: '0'}
                });
                $(this).parent().parent().remove();
                // 清空当前聊天内容
                $(".chat-list").empty();
            }
        });

		console.log(msgObjArr);
        //监听点击用户
        $("body").on("click", ".chatonline li a", function () {
            //取消先前的选中用户
            $(".chatonline li .active .hz-badge").css("opacity", "0");
            $(".chatonline li .active").removeClass("active");
            //设置选中用户为选中状态
            $(this).addClass("active");

            $(this).find('div').text('×');
            $(this).find('div').css("opacity", "1");

            // 清空当前聊天内容
            $(".chat-list").empty();
            // 获取选中用户的Id
            var userId = $(this).find('p').text();
            // 寻找选中用户在消息数组中的下标
            for(var i=0;i<msgObjArr.length;i++){
                if(msgObjArr[i].targetUser!=null&&msgObjArr[i].targetUser.id==userId){
					nowP = i;
					window.parent.nowChat = msgObjArr[i].targetUser.id;
                    initMessage(i);
                    break;
                }
            }
			// 让滚动条直达底部
			$("#chatList").scrollTop($("#chatList").prop('scrollHeight'));
        });

        $("#send").click(function () {
            //消息
            var message = $("#sendMessage").val();
			//当前时间
			var nowTime = new Date();
            //目标用户名
            var targetUserId = $("a.active p").text();
			var userFriendId = msgObjArr[nowP].id;
			var chatHistory = new Object();
			chatHistory.userFriendId=userFriendId;
			chatHistory.message=message;
			chatHistory.sendTime=nowTime;
			chatHistory.isRead='0';
            window.parent.websocket.send(JSON.stringify({
                "type": "1",
                "targetUserId": targetUserId,
                "sourceUserId": user.id,
				"chatHistory": chatHistory
            }));
			nowTime=window.parent.NowTime(nowTime);
			chatHistory.sendTime=nowTime;
			msgObjArr[nowP].chatHistoryList.push(chatHistory);

            $(".chat-list").append(
                "<li class=\"reverse\"><div class=\"chat-content\"><h5>"+user.nickname+"</h5>"+
                "<div class=\"box bg-light-inverse\">"+message+"</div>"+
                "<div class=\"chat-time\">"+nowTime+"</div></div>"+
                "<div class=\"chat-img\"><img src='"+user.profilePhoto+"' alt=\"user\"></div></li>");
            $("#sendMessage").val("");

			// 让滚动条直达底部
			$("#chatList").scrollTop($("#chatList").prop('scrollHeight'));
        })
    });

    function init() {
        //最近聊天好友及其聊天记录
        $.ajax({
            type: 'post',
            url: ctx+"/userFriend/getRecentlyFriend",
            data: {id:user.id},
            async: false,
            success: function (data) {
                msgObjArr = data;
            }
        });

        for(var i=0;i<msgObjArr.length;i++){
            var targetUser = msgObjArr[i].targetUser;
            var userId = targetUser.id;
			var nickname = targetUser.nickname;
            var profilePhoto = targetUser.profilePhoto;
            var userHtml = "<li><a href='#'";
            // 判断当前聊天对象
            if(nowChat!=null&&targetUser.id==nowChat){
                nowP = i;
                userHtml += " class='active'";
            }
            // 添加用户至聊天用户列表
            userHtml+= "><p hidden>"+userId+"</p><img src="+profilePhoto+" alt='user-img' class='img-circle'/><span>"+
                nickname+"</span><div id=\"hz-badge-" + userId + "\" class='hz-badge'>0</div></a></li>";
            $("#friendList").append(userHtml);

            if(nowP!=i){
                // 与当前用户对象聊天记录
                var chatHistoryList=msgObjArr[i].chatHistoryList;
                // 未读消息计数
                var count = 0;
                for(var j=0;j<chatHistoryList.length;j++){
                    if(chatHistoryList[j].isRead=="0"&&chatHistoryList[j].userFriendId!=msgObjArr[i].id){
                        count++;
                    }
                }
                // 展示未读消息数
                $("#hz-badge-" + userId).text(count);
                if(count!=0){
                    $("#hz-badge-" + userId).css("opacity", "1");
                }else{
                    $("#hz-badge-" + userId).css("opacity", "0");
                }
            }
        }
        // 若当前已选中用户则显示聊天记录
        if(nowP!=-1){
            initMessage(nowP);
        }
    }

    // 显示聊天记录
    function initMessage(nowP) {
        var userFriend = msgObjArr[nowP];
        var chatHistoryList = userFriend.chatHistoryList;
        if(chatHistoryList==null){
            return;
        }
        var targetUser = userFriend.targetUser;
		var isReadList = new Array();
        for(var i=0;i<chatHistoryList.length;i++){
            var theMessage=chatHistoryList[i];
			// 判断是否是当前用户发送的消息
            if(theMessage.userFriendId==userFriend.id){
				// 展示当前用户一条消息
                $(".chat-list").append(
                    "<li class=\"reverse\"><div class=\"chat-content\"><h5>"+user.nickname+"</h5>"+
                    "<div class=\"box bg-light-inverse\">"+theMessage.message+"</div>"+
                    "<div class=\"chat-time\">"+formatTime(theMessage.sendTime)+"</div></div>"+
                    "<div class=\"chat-img\"><img src='"+user.profilePhoto+"' alt=\"user\"></div></li>");
            }else{
				// 判断消息是否已读
				if(theMessage.isRead=="0"){
					theMessage.isRead='1';
					isReadList.push(theMessage);
				}
				// 展示聊天对象一条消息
                $(".chat-list").append(
                    "<li><div class=\"chat-img\"><img src='"+targetUser.profilePhoto+"' alt=\"user\"></div>"+
                    "<div class=\"chat-content\"><h5>"+targetUser.nickname+"</h5>"+
                    "<div class=\"box bg-light-info\">"+theMessage.message+"</div>"+
                    "<div class=\"chat-time\">"+formatTime(theMessage.sendTime)+"</div></div></li>");
            }
        }
		// 让滚动条直达底部
		$("#chatList").scrollTop($("#chatList").prop('scrollHeight'));
		// 消息小红点，归0消失
		// $("#hz-badge-" + targetUser.id).text(0);
		// $("#hz-badge-" + targetUser.id).css("opacity", "0");
		// 未读消息数如果大于0，数据库后台全都修改为已读
		if(isReadList.length>0){
			$.ajax({
				type: "POST",
				url: ctx+"/chatHistory/updateIsReadList",
				contentType: "application/json;charset=UTF-8",
				data: JSON.stringify(isReadList),
                async: false,
				success: function(data){
					console.log(data);
				}
			});
			window.parent.getMessage();
		}
    }
	
	// 收到消息处理
	function receiveMessage(data){
		// 判断当前是否选中用户，是否正好和该好友聊天
		if(nowP!=-1&&msgObjArr[nowP].targetUser.id==data.sourceUserId){
			var chatHistoryList = msgObjArr[nowP].chatHistoryList;
			var chatHistory = chatHistoryList[chatHistoryList.length-1];
			var targetUser = msgObjArr[nowP].targetUser;
			$(".chat-list").append(
				"<li><div class=\"chat-img\"><img src='"+targetUser.profilePhoto+"' alt=\"user\"></div>"+
				"<div class=\"chat-content\"><h5>"+targetUser.nickname+"</h5>"+
				"<div class=\"box bg-light-info\">"+chatHistory.message+"</div>"+
				"<div class=\"chat-time\">"+formatTime(chatHistory.sendTime)+"</div></div></li>");
			chatHistory.isRead='1';
			// 让滚动条直达底部
			$("#chatList").scrollTop($("#chatList").prop('scrollHeight'));
			// 后台数据库更新，数据已读
			$.ajax({
				type: "post",
				url: ctx+"/chatHistory/updateIsRead",
				data: {id:chatHistory.id,isRead:chatHistory.isRead}
			});
		}else{
			// 消息小红点+1
			var count=parseInt($("#hz-badge-" + data.sourceUserId).text());
			$("#hz-badge-" + data.sourceUserId).text(count+1);
			$("#hz-badge-" + data.sourceUserId).css("opacity", "1");
		}
	}

	//格式化时间
	function formatTime(time){
		time = time.toString();
		return time.substr(0,10)+" "+time.substr(11,8);
	}
</script>
</body>
</html>